﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Rendering;
using NetCoreCMS.Common;
using NetCoreCMS.IServices;
using NetCoreCMS.Models;
namespace NetCoreCMS.Web.Areas.Admin.Controllers
{
    public class Nav_EditController : ManageController
    {
        private const string WEB_VIEW = "~/Areas/Admin/Views/Settings/nav_edit.cshtml";
        private string action = CMSEnums.ActionEnum.Add.ToString(); //操作类型
        private int id = 0;
        public INavigationService _navigation { get; set; }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            if (filterContext.Result != null)
                return;
            ChkAdminLevel("sys_navigation", CMSEnums.ActionEnum.View.ToString()); //检查权限        
            ActionResult result = View(EDIT_RESULT_VIEW);
            string _action = Request.Query["action"];
            int.TryParse(Request.Query["id"], out this.id);

            if (!string.IsNullOrEmpty(_action) && _action == CMSEnums.ActionEnum.Edit.ToString())
            {
                this.action = CMSEnums.ActionEnum.Edit.ToString();//修改类型
                if (this.id == 0)
                {
                    JscriptMsg("传输参数不正确！", "back");
                    filterContext.Result = result;
                    return;
                }
                if (!_navigation.Exists(this.id))
                {
                    JscriptMsg("导航不存在或已被删除！", "back");
                    filterContext.Result = result;
                    return;
                }
            }
            ViewBag.Action = this.action;
            ViewBag.Id = this.id.ToString();
        }
        // GET: /admin/Nav_Edit/

        public ActionResult Index()
        {
            TreeBind(CMSEnums.NavigationEnum.System.ToString()); //绑定导航菜单
            if (action == CMSEnums.ActionEnum.Edit.ToString())
            {
                ShowInfo(this.id);
            }
            else
            {
                ViewData["model"] = new Navigation();
                ViewBag.ClientScript = "$('#txtName').attr('ajaxurl', '/Admin/Admin_Ajax?action=navigation_validate');";
            }
            return View(WEB_VIEW);
        }

        [HttpPost]
        public ActionResult SubmitSave()
        {
            ActionResult result = View(EDIT_RESULT_VIEW);
            if (action == CMSEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("sys_navigation", CMSEnums.ActionEnum.Edit.ToString()); //检查权限
                if (!DoEdit(this.id))
                {
                    ViewBag.ClientScript = JscriptMsg("保存过程中发生错误！", "back");
                    return result;
                }
                ViewBag.ClientScript = JscriptMsg("修改导航菜单成功！", "../nav_list/index", "parent.loadMenuTree");
            }
            else //添加
            {
                ChkAdminLevel("sys_navigation", CMSEnums.ActionEnum.Add.ToString()); //检查权限
                if (!DoAdd())
                {
                    ViewBag.ClientScript = JscriptMsg("保存过程中发生错误！", "back");
                    return result;
                }
                ViewBag.ClientScript = JscriptMsg("添加导航菜单成功！", "../nav_list/index", "parent.loadMenuTree");
            }
            return result;
        }

        #region 绑定导航菜单=============================
        private void TreeBind(string nav_type)
        {
            var dt = _navigation.GetList(0, nav_type);
            List<SelectListItem> parentList = new List<SelectListItem>();
            parentList.Add(new SelectListItem() { Text = "无父级导航", Value = "0" });
            foreach (Navigation dr in dt)
            {
                string Id = dr.id.ToString();
                int ClassLayer = int.Parse(dr.class_layer.ToString());
                string Title = dr.title;
                if (ClassLayer == 1)
                {
                    parentList.Add(new SelectListItem() { Text = Title, Value = Id });
                }
                else
                {
                    Title = "├ " + Title;
                    Title = Utils.StringOfChar(ClassLayer - 1, "　") + Title;
                    parentList.Add(new SelectListItem() { Text = Title, Value = Id });
                }
            }
            ViewData["selectListItems"] = parentList;
        }
        #endregion

        #region 赋值操作=================================
        private void ShowInfo(int _id)
        {
            var model = _navigation.GetModel(_id);
            ViewData["model"] = model;
            ViewBag.ClientScript = "$('#txtName').attr('ajaxurl', '/Admin/Admin_Ajax?action=navigation_validate&old_name=" + Utils.UrlEncode(model.name) + "');";
        }
        #endregion

        #region 增加操作=================================
        private bool DoAdd()
        {
            try
            {
                Navigation model = new Navigation();

                model.nav_type = CMSEnums.NavigationEnum.System.ToString();
                model.name = Request.Form["txtName"].FirstOrDefault().Trim();
                model.title = Request.Form["txtTitle"].FirstOrDefault().Trim();
                model.sub_title = Request.Form["txtSubTitle"].FirstOrDefault().Trim();
                model.icon_url = Request.Form["txtIconUrl"].FirstOrDefault().Trim();
                model.link_url = Request.Form["txtLinkUrl"].FirstOrDefault().Trim();
                model.sort_id = int.Parse(Request.Form["txtSortId"].FirstOrDefault().Trim());
                model.is_lock = Request.Form["cbIsLock"].FirstOrDefault().ToLower().IndexOf("true") >= 0 ? 1 : 0;
                model.remark = Request.Form["txtRemark"].FirstOrDefault().Trim();
                model.parent_id = int.Parse(Request.Form["ddlParentId"]);

                //添加操作权限类型
                string action_type_str = string.Empty;
                foreach (KeyValuePair<string, string> kv in Utils.ActionType())
                {
                    if (Request.Form["cblActiontype_" + kv.Key].FirstOrDefault().ToLower().IndexOf("true") >= 0)
                    {
                        action_type_str += kv.Key + ",";
                    }
                }
                model.action_type = Utils.DelLastComma(action_type_str);
                if (_navigation.Add(model) > 0)
                {
                    AddAdminLog(CMSEnums.ActionEnum.Add.ToString(), "添加导航菜单:" + model.title); //记录日志
                    return true;
                }
            }
            catch
            {
                return false;
            }
            return false;
        }
        #endregion

        #region 修改操作=================================
        private bool DoEdit(int _id)
        {
            try
            {
                var model = _navigation.GetModel(_id);

                model.name = Request.Form["txtName"].FirstOrDefault().Trim();
                model.title = Request.Form["txtTitle"].FirstOrDefault().Trim();
                model.sub_title = Request.Form["txtSubTitle"].FirstOrDefault().Trim();
                model.icon_url = Request.Form["txtIconUrl"].FirstOrDefault().Trim();
                model.link_url = Request.Form["txtLinkUrl"].FirstOrDefault().Trim();
                model.sort_id = int.Parse(Request.Form["txtSortId"].FirstOrDefault().Trim());
                model.is_lock = Request.Form["cbIsLock"].FirstOrDefault().ToLower().IndexOf("true") >= 0 ? 1 : 0;
                model.remark = Request.Form["txtRemark"].FirstOrDefault().Trim();
                if (model.is_sys == 0)
                {
                    int parentId = int.Parse(Request.Form["ddlParentId"]);
                    //如果选择的父ID不是自己,则更改
                    if (parentId != model.id)
                    {
                        model.parent_id = parentId;
                    }
                }

                //添加操作权限类型
                string action_type_str = string.Empty;
                foreach (KeyValuePair<string, string> kv in Utils.ActionType())
                {
                    if (Request.Form["cblActiontype_" + kv.Key].FirstOrDefault().ToLower().IndexOf("true") >= 0)
                    {
                        action_type_str += kv.Key + ",";
                    }
                }
                model.action_type = Utils.DelLastComma(action_type_str);
                if (_navigation.Update(model))
                {
                    AddAdminLog(CMSEnums.ActionEnum.Add.ToString(), "修改导航菜单:" + model.title); //记录日志
                    return true;
                }
            }
            catch
            {
                return false;
            }
            return false;
        }
        #endregion
    }
}
